package com.example.jwt.filter.security;


import com.example.jwt.entity.security.JwtAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Jwt 登陆拦截器, 应该放在 UsernamePasswordAuthenticationFilter 前面
 */
public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String username = this.obtainUsername(request);
        username = username != null ? username : "";
        username = username.trim();
        String password = this.obtainPassword(request);
        password = password != null ? password : "";

        JwtAuthenticationToken authRequest = new JwtAuthenticationToken(username, password);
        // 添加一些附带信息
        authRequest.setDetails(new WebAuthenticationDetails(request));
        // 由于自定义了 AuthenticationToken, 所以还需要自定义一个 Provider 来支持此 AuthenticationToken 的校验
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
